<template>
	<view class="login-container">
		<!-- 头部标题 -->
		<view class="header">
			<text class="title">欢迎登录</text>
		</view>

		<!-- 登录方式切换 -->
		<!-- <view class="tab-container">
			<view class="tab-item" :class="{ active: loginType === 'password' }" @click="switchLoginType('password')">
				密码登录
			</view>
			<view class="tab-item" :class="{ active: loginType === 'code' }" @click="switchLoginType('code')">
				验证码登录
			</view>
		</view> -->

		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 手机号输入 -->
			<view class="input-group">
				<text class="label">手机号</text>
				<input v-model="form.phone" type="number" placeholder="请输入手机号" maxlength="11" class="input" @blur="validatePhone" />
				<text class="error-msg">{{ errors.phone }}</text>
			</view>

			<!-- 密码输入（密码登录模式） -->
			<view class="input-group" v-if="loginType === 'password'">
				<text class="label">密码</text>
				<input v-model="form.password" password placeholder="请输入密码" class="input" @blur="validatePassword" />
				<text class="error-msg">{{ errors.password }}</text>
			</view>

			<!-- 验证码输入（验证码登录模式） -->
			<view class="input-group" v-else>
				<text class="label">验证码</text>
				<view class="code-input-wrapper">
					<input v-model="form.code" type="number" placeholder="请输入验证码" maxlength="4"
						class="input code-input" />
					<button class="get-code-btn" :disabled="countdown > 0 || !canGetCode" @click="getSMSCode">
						{{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
					</button>
				</view>
				<text class="error-msg">{{ errors.code }}</text>
			</view>

			<!-- 登录按钮 -->
			<button class="login-btn primary-btn" :disabled="!canSubmit" @click="handleLogin">
				登录
			</button>
			
			<!-- 去注册 -->
			<view class="register-link">
			  <text>没有账号？</text>
			  <text class="link" @click="navigateToRegister">去注册</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onUnmounted, ref, watch, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/userStore.js'
import { createVerifyCode, login, getReviewsByDriverId } from '@/api/user.js'
import { auditStatusEnum } from '@/utils/enums'
import { getToken, setToken } from '@/utils/auth' 

const driver = useUserStore()

const loginType = ref('code') // password / code
const form = ref({
	phone: '',
	password: '',
	code: ''
})
const errors = ref({
	phone: '',
	password: '',
	code: ''
})
const countdown = ref(0)
let timer = null

let canGetCode = computed(() => {
	return /^1[3-9]\d{9}$/.test(form.value.phone)
})

let canSubmit = computed(() => {
	let matched = /^1[3-9]\d{9}$/.test(form.value.phone) 
	if (loginType.value === 'password') {
		return matched && form.value.password.length >= 6
	} else {
		return matched && form.value.code.length === 4
	}
	return true
})

// 切换登录方式
function switchLoginType(type) {
	loginType.value = type
}

// 验证手机号
function validatePhone() {
	if (!form.value.phone) {
		errors.value.phone = '请输入手机号'
	} else if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
		errors.value.phone = '请输入正确的手机号'
	} else {
		errors.value.phone = ''
	}
}

// 验证密码
/* function validatePassword() {
	if (!form.value.password) {
		errors.value.password = '请输入密码'
	} else if (form.value.password.length < 6) {
		errors.value.password = '密码至少6位'
	} else {
		errors.value.password = ''
	}
} */

// 获取短信验证码
function getSMSCode() {
	validatePhone()
	if (errors.value.phone) return

	// 模拟发送验证码
	uni.showLoading({
		title: '发送中...'
	})
	createVerifyCode(form.value.phone).then(res => {
		// 开始倒计时
		startCountdown()
		// 关闭加载
		uni.hideLoading()
		uni.showToast({
			title: '验证码已发送' + res.data,
			icon: 'none'
		})
	}).catch(err => {
		uni.hideLoading()
	})
}

// 开始倒计时
function startCountdown() {
	countdown.value = 60
	timer = setInterval(() => {
		if (countdown.value <= 0) {
			clearInterval(timer)
			return
		}
		countdown.value--
	}, 1000)
}

function navigateToRegister () {
	uni.navigateTo({
		url: '/pages/login-and-register/register'
	})
}

// 处理登录
function handleLogin () {
	if (!canSubmit.value) return
	uni.showLoading({
		title: '登录中...'
	})
	login({
		phone: form.value.phone,
		verifyCode: form.value.code
	}).then(res => {
		uni.hideLoading()
		uni.showToast({
			title: '登录成功',
			icon: 'none',
			success: () => {
				setToken(res.data)
				// 设置当前用户
				driver.refreshCurrentDriver().then(res => {
					// 看是否需要重定向
					doRedirect()
				})
				
			}
		})
	}).catch(err => {
		uni.hideLoading()
	})
}

// 进入此页面或者点击登录的时候，判断用户是否提交过身份认证。若没有，需要重定向；否则都跳到首页
function doRedirect () {
	if (driver.getCurrentDriver().auditStatus === auditStatusEnum.PENDING.value) {
		// 1. 如果司机状态为待审核，判断他是否提交过审核资料
		getReviewsByDriverId(driver.getCurrentDriver().id).then(res => {
			if (res.data && res.data.length > 0) {
				// 提交过
				uni.reLaunch({
					url: '/pages/index/index'
				})
				return
			} else {
				// 没提交过
				uni.reLaunch({
					url: '/pages/mine/edit-info',
					success: () => {
						uni.showToast({
							duration: 2500,
							icon: 'none',
							title: '请您提交审核信息'
						})
					}
				})
			}
		})
	} else if (driver.getCurrentDriver().auditStatus === auditStatusEnum.PASS.value) {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}
}

onLoad(() => {
	// 只要清了后台，那么每次打开APP，都会先进入login页(page.json里的第一页)。
	// 每进到这个页面，若司机ID存在，判断要不要重定向
	if (driver.getCurrentDriver().id) {
		doRedirect()
	}
})

onUnmounted(() => {
	if (timer) clearInterval(timer)
})

</script>

<style lang="scss" scoped>
* {
	box-sizing: border-box;
}
.login-container {
	padding: 40rpx 60rpx;
	min-height: 100vh;
	background: #f8f8f8;

	.header {
		margin: 80rpx 0 60rpx;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.tab-container {
		display: flex;
		margin-bottom: 60rpx;
		border-bottom: 2rpx solid #eee;

		.tab-item {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			font-size: 32rpx;
			color: #999;
			position: relative;

			&.active {
				color: #2979ff;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: -2rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 80rpx;
					height: 4rpx;
					background: #2979ff;
					border-radius: 2rpx;
				}
			}
		}
	}

	.form-container {
		.input-group {
			margin-bottom: 40rpx;

			.label {
				display: block;
				margin-bottom: 16rpx;
				font-size: 28rpx;
				color: #666;
			}

			.input {
				height: 88rpx;
				padding: 0 24rpx;
				border-radius: 12rpx;
				border: 2rpx solid #ddd;
				background: #fff;
				font-size: 32rpx;
				&:hover {
					border: 2rpx solid #3f89ff;
				}
			}

			.code-input-wrapper {
				display: flex;

				.code-input {
					flex: 1;
					margin-right: 20rpx;
				}

				.get-code-btn {
					width: 200rpx;
					height: 88rpx;
					line-height: 88rpx;
					background: #f0f0f0;
					color: #2979ff;
					font-size: 28rpx;
					padding: 0;
				
					&[disabled] {
						color: #999;
						background: #f5f5f5;
					}
				}
				
			}

			.error-msg {
				display: block;
				margin-top: 10rpx;
				color: #f56c6c;
				font-size: 24rpx;
			}
		}

		.login-btn {
			margin-top: 60rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 12rpx;
			color: #fff;
			font-size: 32rpx;
			
			&[disabled] {
				opacity: 0.6;
			}
		}

		
		.register-link {
		  margin-top: 40rpx;
		  text-align: center;
		  font-size: 28rpx;
		  color: #666;
		  
		  .link {
			color: #2979ff;
		  }
		}
	}
}
</style>